/**  定义关于我们模块相关的接口 */
const express = require('express');
const router = express.Router();
const Joi = require('joi');
const Response = require('../utils/Response.js');

// 引入mysql连接池
const pool = require('../utils/db.js');

/**
 * 通过类别ID查询类别下内容
 * @param:
 *   详见接口文档
 * @return:
 *   {code:200, msg:'ok', data:[]}
 */
router.get('/about/query', async (req, resp) => {
  // 获取请求参数   get请求的参数封装在req.query中
  let { page, pagesize, id } = req.query;

  //TODO 服务端表单验证  如果验证通过那么继续后续业务  如果验证不通过，则直接返回参数异常
  let schema = Joi.object({
    id: Joi.number().required(), // cid必须是数字，必填
    page: Joi.number().required(), // page必须是数字，必填
    pagesize: Joi.number().integer().max(100).required(), // pagesize必须是不大于100的数字，必填
  });
  let { error, value } = schema.validate(req.query);
  if (error) {
    resp.send(Response.error(400, error));
    return; // 结束
  }

  // 执行查询数组业务
  try {
    id = parseInt(id);
    let startIndex = (page - 1) * pagesize;
    let size = parseInt(pagesize);
    let sql = 'select * from about_content where ac_id=? limit ?,?';
    let result = await pool.querySync(sql, [id, startIndex, size]);
    // 执行查询总条目数
    let sql2 = 'select count(*) as count from about_content where ac_id=?';
    let result2 = await pool.querySync(sql2, [id]);
    let total = result2[0].count;
    resp.send(
      Response.ok({ page: parseInt(page), pagesize: size, total, result })
    );
  } catch (error) {
    resp.send(Response.error(error));
  }
});

// 查询所有的标题和id
router.get('/about/title', (req, resp) => {
  let { error, value } = req.query;
  if (error) {
    resp.send(Response.error(400, error));
    return; // 结束
  }
  // 执行查询业务
  let sql = `select aid,ac_id,acname,atitle from about_content abc join about_catalog ac on abc.ac_id=ac.acid  order by ac_id`;
  pool.query(sql, (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    if (result && result.length == 0) {
      // 没查到
      resp.send(Response.ok(null));
    } else {
      resp.send(Response.ok(result));
    }
  });
});

// 将router对象导出
module.exports = router;
